package com.gosuncn.FileCopy;


import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.Jedis;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * HttpClients方式实现跨服务器上传文件  通过redis进行缓存
 */
public class httpClient {



    public String UploadFileByHttpClient(List<File> fileList,String url) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        Jedis jedis = new Jedis("127.0.0.1", 6379);

        try {
            //通过post请求
            HttpPost httpPost = new HttpPost(url);
            //用Multipart进行文件的上传  HttpMultipartMode.RFC6532防止文件乱码
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            //获取缓存中的已上传的文件路径
            List<String> folderList = jedis.lrange("fileName", 0, -1);

            for (File file : fileList) {
                //当前文件的绝对路径+相对路径
                String filePath = file.getAbsolutePath();
                // D:\oldpath\zxl\123.txt 获取给定目录下的所有文件目录 zxl\123.txt
                String folder = filePath.substring(filePath.indexOf("\\", 3)+1);

//                for (String s : folderList) {
//                    System.out.println(s);
//                }
                //判断字符串是否在列表里面  存在返回true   必须要组装数据，在folderList=[""zxl\\ceshi.txt"",""ttt.txt"",""数据\\zxlsd.txt""]
                if (!folderList.contains("\""+folder.replace("\\","\\\\")+"\"")){

                    builder.addBinaryBody("fileName",file, ContentType.MULTIPART_FORM_DATA,folder); //二进制文件

                    //防止传递参数中文乱码
                    StringBody folder1 = new StringBody(folder, ContentType.create("text/plain", Consts.UTF_8));
                    builder.addPart("name",folder1);
                    //设置参数，后台可以通过String params1 绑定入params1赋值（会中文乱码）
//                    builder.addTextBody("name",folder);
                    //设置编码
                    builder.setCharset(Consts.UTF_8);

                    HttpEntity entity = builder.build();
                    //设置请求参数
                    httpPost.setEntity(entity);
                    //提交响应
                    response = httpClient.execute(httpPost);
                    //接收调用外部接口响应的内容
                    Header[] headers = response.getHeaders("token");
                    for (Header header : headers) {
                        System.out.println("响应的状态码： "+response.getStatusLine().getStatusCode());
                        System.out.println(URLDecoder.decode(String.valueOf(header),"UTF-8"));
                    }
                }else {
                    System.out.println("目标服务器已存在"+folder+"文件");
                }
            }

            return "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败";
        } finally {
            try {
                //定期清除缓存
                jedis.expire("fileName",60);
                //关闭连接
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        String url = "http://localhost:8081/file/fileupload";
        String path = "D:\\dirA";
        File file = new File(path);
//        String name = "xiaolong.txt";
        FileUtils allfile = new FileUtils(file);
        //获取所有的文件
        ArrayList<File> fileArrayList = allfile.getAllFile();
        httpClient httpClient = new httpClient();
        //执行上传
        httpClient.UploadFileByHttpClient(fileArrayList,url);


//        Jedis jedis = new Jedis("127.0.0.1", 6379);
//        System.out.println(jedis.lrange("ad", 0, -1));
    }

}
